package com.rickpan.repository;

import com.rickpan.entity.PaymentOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 支付订单数据访问接口
 */
@Repository
public interface PaymentOrderRepository extends JpaRepository<PaymentOrder, Long> {

    /**
     * 根据订单号查找订单
     */
    Optional<PaymentOrder> findByOrderNo(String orderNo);

    /**
     * 根据用户ID查找订单列表
     */
    List<PaymentOrder> findByUserIdOrderByCreatedAtDesc(Long userId);

    /**
     * 分页根据用户ID查找订单列表
     */
    Page<PaymentOrder> findByUserId(Long userId, Pageable pageable);

    /**
     * 根据用户ID和状态查找订单
     */
    List<PaymentOrder> findByUserIdAndStatus(Long userId, PaymentOrder.PaymentStatus status);

    /**
     * 查找已过期但未处理的订单
     */
    @Query("SELECT p FROM PaymentOrder p WHERE p.status = 'PENDING' AND p.expiresAt < :now")
    List<PaymentOrder> findExpiredPendingOrders(@Param("now") LocalDateTime now);

    /**
     * 统计用户的成功支付订单数量
     */
    @Query("SELECT COUNT(p) FROM PaymentOrder p WHERE p.userId = :userId AND p.status = 'PAID'")
    Long countPaidOrdersByUserId(@Param("userId") Long userId);

    /**
     * 根据第三方交易号查找订单
     */
    Optional<PaymentOrder> findByTradeNo(String tradeNo);

    /**
     * 查找指定时间范围内的支付成功订单
     */
    @Query("SELECT p FROM PaymentOrder p WHERE p.status = 'PAID' AND p.paidAt BETWEEN :startTime AND :endTime")
    List<PaymentOrder> findPaidOrdersBetween(@Param("startTime") LocalDateTime startTime, 
                                           @Param("endTime") LocalDateTime endTime);
}